import { createStore } from "vuex";

import { getStore, setStore, delStore } from "@/common/store.js";

const store = createStore({
  state: {
    AppVersion: "V1.3.8", //当前app版本号
    userInfo: getStore("userInfo") || {},
    token: getStore("token") || "",
    tokenType: getStore("tokenType") || "",
    refreshToken: getStore("refreshToken"),
    userType: getStore("userType"),
    userId: getStore("userId"), //用户ID
    realName: getStore("realName"), //用户真实姓名
    fileDomain: "",
    empIdCard: getStore("empIdCard"), //身份证号
    ownerName: "", //所属企业名称
    empInfoId: getStore("empInfoId"), //企业人员id
    // phone: getStore('phone'), //用户手机号
    updateUrl: "", //app更新接口
    isUpdate: false, //true:有新版本  false：没有新版本
    fileUrl: "", //图片文件前缀
    roadCheckInfo: {},
    roadCheckEssential: {},
    temp: {},
    //-----------------企业--------------//
    newVersion: "", //新版本号
    oldVersion: "", //旧版本号
    pdfUrl: "", //pdf下载路径
    pdfLocalUrl: "", //pdf下载完成本地路径
    clientId: "dzyd_app", // 客户端id
    clientSecret: "yd_app_secret", // 客户端密钥
    locationResult: {},
    hasLogin: false,
    isUniverifyLogin: false,
    loginProvider: "",
    openid: null,
    testvuex: false,
    colorIndex: 0,
    colorList: ["#FF0000", "#00FF00", "#0000FF"],
    noMatchLeftWindow: true,
    active: "componentPage",
    leftWinActive: "/pages/component/view/view",
    activeOpen: "",
    menu: [],
    univerifyErrorMsg: "",
    regionData: getStore("regionData") || [], // 存储地区数据
    billPdfDomain: getStore("billPdfDomain"), // 文件服务器地址
    // 临时信息
    tempData: getStore("tempData") || null,
    // 动态tabbar
    tabBarType: getStore("tabBarType") || "",
    loadFillData: null,
    unloadFillData: null,
    info: {},
  },
  mutations: {
    set_temp(state, parm) {
      const { key, value } = parm;
      state.temp[key] = value;
      setStore("temp", state.temp);
    },
    // set_regionData(state, parm) {
    // 	state.token = parm;
    // 	setStore('regionData', parm);
    // },
    set_token(state, token) {
      state.token = token;
      setStore("token", token);
    },
    set_tokenType(state, tokenType) {
      state.tokenType = tokenType;
      setStore("tokenType", tokenType);
    },
    set_userInfo(state, parm) {
      state.userInfo = parm;
      setStore("userInfo", parm);
    },

    tokenType(state, parm) {
      state.tokenType = parm;
      setStore("tokenType", parm);
    },
    refreshToken(state, parm) {
      state.refreshToken = parm;
      setStore("refreshToken", parm);
    },
    userId(state, parm) {
      state.userId = parm;
      setStore("userId", parm);
    },
    realName(state, parm) {
      state.realName = parm;
      setStore("realName", parm);
    },
    userType(state, parm) {
      state.userType = parm;
      setStore("userType", parm);
    },
    empIdCard(state, parm) {
      state.empIdCard = parm;
      setStore("empIdCard", parm);
    },

    ownerName(state, parm) {
      state.ownerName = parm;
      setStore("ownerName", parm);
    },
    empInfoId(state, parm) {
      state.empInfoId = parm;
      setStore("empInfoId", parm);
    },

    logOut(state) {
      state.token = "";
      state.tokenType = "";
      delStore("token");
      delStore("tokenType");
      state.userId = "";
      delStore("userId");
      state.realName = "";
      delStore("realName");
      state.userType = "";
      delStore("userType");
      state.empIdCard = "";
      delStore("empIdCard");
      state.ownerName = "";
      delStore("ownerName");
      state.empInfoId = "";
      delStore("empInfoId");
      state.phone = "";
      delStore("phone");
      state.userInfo = "";
      delStore("userInfo");
      uni.removeStorage({
        key: "base_login_name",
      });
    },
    //路检路查详情
    setroadCheckInfo(state, parm) {
      state.roadCheckInfo = parm;
    },

    //路检路查详情
    setroadCheckEssential(state, parm) {
      state.roadCheckEssential = parm;
    },

    //------------------------企业------------//
    set_tempData(state, parm) {
      state.tempData = parm;
      setStore("tempData", parm);
    },
    set_regionData(state, parm) {
      state.regionData = parm;
      setStore("regionData", parm);
    },
    set_BillPdfDomain(state, parm) {
      state.billPdfDomain = parm;
      setStore("billPdfDomain", parm);
    },

    phone(state, parm) {
      state.phone = parm;
      setStore("phone", parm);
    },

    //==============================================

    login(state, provider) {
      state.hasLogin = true;
      state.loginProvider = provider;
    },
    logout(state) {
      state.hasLogin = false;
      state.openid = null;
    },
    setOpenid(state, openid) {
      state.openid = openid;
    },
    setTestTrue(state) {
      state.testvuex = true;
    },
    setTestFalse(state) {
      state.testvuex = false;
    },
    setColorIndex(state, index) {
      state.colorIndex = index;
    },
    setMatchLeftWindow(state, matchLeftWindow) {
      state.noMatchLeftWindow = !matchLeftWindow;
    },
    setActive(state, tabPage) {
      state.active = tabPage;
    },
    setLeftWinActive(state, leftWinActive) {
      state.leftWinActive = leftWinActive;
    },
    setActiveOpen(state, activeOpen) {
      state.activeOpen = activeOpen;
    },
    setMenu(state, menu) {
      state.menu = menu;
    },
    setUniverifyLogin(state, payload) {
      typeof payload !== "boolean" ? (payload = !!payload) : "";
      state.isUniverifyLogin = payload;
    },
    setUniverifyErrorMsg(state, payload = "") {
      state.univerifyErrorMsg = payload;
    },

    set_tabBarType(state, type) {
      state.univerifyErrorMsg = type;
      setStore("tabBarType", type);
    },
    setloadFillData(state, data) {
      state.loadFillData = data;
    },
    setunloadFillData(state, data) {
      state.unloadFillData = data;
    },
  },
  getters: {
    get_temp(state) {
      return state.temp;
    },
    getToken: (state) => state.token || getStore("token") || "",
    getTokenType: (state) => state.tokenType || getStore("tokenType") || "",
    getUserInfo(state) {
      return state.userInfo;
    },
    AppVersion(state) {
      return state.AppVersion;
    },
    //-----企业-------//
    getTempData(state) {
      return state.tempData;
    },
    getRegionData(state) {
      return state.regionData;
    },
    getBillPdfDomain(state) {
      return state.billPdfDomain;
    },
    currentColor(state) {
      return state.colorList[state.colorIndex];
    },
    getRefreshToken(state) {
      return state.refreshToken;
    },
    getClientId(state) {
      return state.clientId;
    },
    getClientSecret(state) {
      return state.clientSecret;
    },
    getUserType(state) {
      return state.userType == 2 ? 0 : 1; // 1==驾押人员   0== 企业管理人员
    },
    userType(state) {
      return state.userType;
    },
    getEmpIdCard(state) {
      return state.empIdCard;
    },
    getEmpInfoId(state) {
      return state.empInfoId;
    },
    getRealName(state) {
      return state.realName;
    },
    getPhone(state) {
      return state.phone;
    },
    getOwnerName(state) {
      return state.userInfo && state.userInfo.ownerName;
    },
  },
  actions: {
    // lazy loading openid
    getUserOpenId: async function ({ commit, state }) {
      return await new Promise((resolve, reject) => {
        if (state.openid) {
          resolve(state.openid);
        } else {
          uni.login({
            success: (data) => {
              commit("login");
              setTimeout(function () {
                //模拟异步请求服务器获取 openid
                const openid = "123456789";
                console.log("uni.request mock openid[" + openid + "]");
                commit("setOpenid", openid);
                resolve(openid);
              }, 1000);
            },
            fail: (err) => {
              console.log(
                "uni.login 接口调用失败，将无法正常使用开放接口等服务",
                err
              );
              reject(err);
            },
          });
        }
      });
    },
    getPhoneNumber: function ({ commit }, univerifyInfo) {
      return new Promise((resolve, reject) => {
        uni.request({
          url: "https://97fca9f2-41f6-449f-a35e-3f135d4c3875.bspapp.com/http/univerify-login",
          method: "POST",
          data: univerifyInfo,
          success: (res) => {
            const data = res.data;
            if (data.success) {
              resolve(data.phoneNumber);
            } else {
              reject(res);
            }
          },
          fail: (err) => {
            reject(res);
          },
        });
      });
    },
    setLoginInfo({ commit }, { token, tokenType }) {
      commit("set_token", token);
      commit("set_tokenType", tokenType);
    },
  },
});
export default store;
